<template>
    <el-menu
            :default-active="activeIndex"
            @select="menuHandle"
            menu-trigger="hover"
            class="el-menu-navbar"
            mode="horizontal">
        <el-menu-item index="/">首页</el-menu-item>
        <el-menu-item index="/channel">Live</el-menu-item>
        <template v-if="user">
            <el-menu-item index="/favorite">
                收藏夹
            </el-menu-item>
            <el-menu-item index="/history">
                历史记录
            </el-menu-item>
            <el-submenu index="/center">
                <template slot="title">{{ user.name }}</template>
                <el-menu-item index="/logout">
                    退出登录
                </el-menu-item>
            </el-submenu>
        </template>
        <template v-else>
            <el-menu-item index="/login">
                登录
            </el-menu-item>
            <el-menu-item index="/register">
                注册
            </el-menu-item>
        </template>
    </el-menu>
</template>

<script>
    export default {
        name: "MainNavbar",
        data() {
            return {
                activeIndex: ''
            }
        },
        methods: {
            menuHandle(index) {
                if (location.pathname === index) {
                    return;
                }
                if ('/logout' === index) {
                    this.logoutHandle(index);
                } else {
                    location.href = index
                }
            },
            logoutHandle(url) {
                this.$axios.post(url)
                    .then((response) => {
                        location.href = '/login'
                    })
                    .catch((error) => {
                        console.log(error)
                    })
            }
        },
        mounted() {
            this.activeIndex = '/' + location.pathname.split('/')[1]
        },
        props: ['user']
    }
</script>

<style scoped lang="scss">
    .el-menu-navbar {
        li:last-child {
            float: right;
        }
    }
</style>